package com.bringspring.system.base.controller;

import com.bringspring.common.base.ActionResult;
import com.bringspring.common.base.Pagination;
import com.bringspring.common.base.vo.DownloadVO;
import com.bringspring.common.base.vo.ListVO;
import com.bringspring.common.base.vo.PageListVO;
import com.bringspring.common.base.vo.PaginationVO;
import com.bringspring.common.config.ConfigValueUtil;
import com.bringspring.common.constant.MsgCode;
import com.bringspring.common.exception.DataException;
import com.bringspring.common.util.FileUtil;
import com.bringspring.common.util.JsonUtil;
import com.bringspring.common.util.StringUtils;
import com.bringspring.common.util.enums.ModuleTypeEnum;
import com.bringspring.common.util.file.fileinfo.DataFileExport;
import com.bringspring.system.base.entity.BillRuleEntity;
import com.bringspring.system.base.model.billrule.BillRuleCrForm;
import com.bringspring.system.base.model.billrule.BillRuleInfoVO;
import com.bringspring.system.base.model.billrule.BillRuleListVO;
import com.bringspring.system.base.model.billrule.BillRuleUpForm;
import com.bringspring.system.base.service.BillRuleService;
import com.bringspring.system.base.util.JsonUtilEx;
import com.bringspring.system.permission.entity.UserEntity;
import com.bringspring.system.permission.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 单据规则
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2017年9月27日 上午9:18
 */
@Api(tags = "单据规则", value = "BillRule")
@RestController
@RequestMapping("/api/system/BillRule")
public class BillRuleController {

    @Autowired
    private DataFileExport fileExport;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private BillRuleService billRuleService;
    @Autowired
    private UserService userService;

    /**
     * 列表
     *
     * @param pagination 分页参数
     * @return ignore
     */
    @ApiOperation("获取单据规则列表(带分页)")
    @GetMapping
    public ActionResult<PageListVO<BillRuleListVO>> list(Pagination pagination) {
        List<BillRuleEntity> list = billRuleService.getList(pagination);
        List<BillRuleListVO> listVO = new ArrayList<>();
        list.forEach(entity->{
            BillRuleListVO vo = JsonUtil.getJsonToBean(entity, BillRuleListVO.class);
            UserEntity userEntity = userService.getInfo(entity.getCreatorUserId());
            if(userEntity != null){
                vo.setCreatorUserId(userEntity.getRealName());
            }
            listVO.add(vo);
        });
        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(listVO, paginationVO);
    }

    /**
     * 列表
     *
     * @return ignore
     */
    @ApiOperation("获取单据规则下拉框")
    @GetMapping("/Selector")
    public ActionResult selectList() {
        List<BillRuleEntity> list = billRuleService.getList();
        List<BillRuleListVO> vo = JsonUtil.getJsonToList(list, BillRuleListVO.class);
        ListVO listVO = new ListVO();
        listVO.setList(vo);
        return ActionResult.success(listVO);
    }


    /**
     * 更新组织状态
     *
     * @param id 主键值
     * @return ignore
     */
    @ApiOperation("更新单据规则状态")
    @PutMapping("/{id}/Actions/State")
    public ActionResult update(@PathVariable("id") String id) {
        BillRuleEntity entity = billRuleService.getInfo(id);
        if (entity != null) {
            if ("1".equals(String.valueOf(entity.getEnabledMark()))) {
                entity.setEnabledMark(0);
            } else {
                entity.setEnabledMark(1);
            }
            billRuleService.update(entity.getId(), entity);
            return ActionResult.success(MsgCode.SU004.get());
        }
        return ActionResult.fail(MsgCode.FA002.get());
    }

    /**
     * 信息
     *
     * @param id 主键值
     * @return ignore
     */
    @ApiOperation("获取单据规则信息")
    @GetMapping("/{id}")
    public ActionResult<BillRuleInfoVO> info(@PathVariable("id") String id) throws DataException {
        BillRuleEntity entity = billRuleService.getInfo(id);
        BillRuleInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, BillRuleInfoVO.class);
        return ActionResult.success(vo);
    }

    /**
     * 获取单据流水号
     *
     * @param enCode 参数编码
     * @return ignore
     */
    @ApiOperation("获取单据流水号(工作流调用)")
    @GetMapping("/BillNumber/{enCode}")
    public ActionResult getBillNumber(@PathVariable("enCode") String enCode) throws DataException {
        String data = billRuleService.getBillNumber(enCode, false);
        return ActionResult.success("获取成功", data);
    }

    /**
     * 新建
     *
     * @param billRuleCrForm 实体对象
     * @return ignore
     */
    @ApiOperation("添加单据规则")
    @PostMapping
    public ActionResult create(@RequestBody @Valid BillRuleCrForm billRuleCrForm) {
        BillRuleEntity entity = JsonUtil.getJsonToBean(billRuleCrForm, BillRuleEntity.class);
        if (billRuleService.isExistByFullName(entity.getFullName(), entity.getId())) {
            return ActionResult.fail(MsgCode.EXIST001.get());
        }
        if (billRuleService.isExistByEnCode(entity.getEnCode(), entity.getId())) {
            return ActionResult.fail(MsgCode.EXIST002.get());
        }
        billRuleService.create(entity);
        return ActionResult.success(MsgCode.SU001.get());
    }

    /**
     * 更新
     *
     * @param billRuleUpForm 实体对象
     * @param id             主键值
     * @return ignore
     */
    @ApiOperation("修改单据规则")
    @PutMapping("/{id}")
    public ActionResult update(@PathVariable("id") String id, @RequestBody BillRuleUpForm billRuleUpForm) {
        BillRuleEntity entity = JsonUtil.getJsonToBean(billRuleUpForm, BillRuleEntity.class);
        if (billRuleService.isExistByFullName(entity.getFullName(), id)) {
            return ActionResult.fail(MsgCode.EXIST001.get());
        }
        if (billRuleService.isExistByEnCode(entity.getFullName(), id)) {
            return ActionResult.fail(MsgCode.EXIST002.get());
        }
        boolean flag = billRuleService.update(id, entity);
        if (!flag) {
            return ActionResult.fail(MsgCode.FA002.get());
        }
        return ActionResult.success(MsgCode.SU004.get());
    }

    /**
     * 删除
     *
     * @param id 主键值
     * @return ignore
     */
    @ApiOperation("删除单据规则")
    @DeleteMapping("/{id}")
    public ActionResult delete(@PathVariable("id") String id) {
        BillRuleEntity entity = billRuleService.getInfo(id);
        if (entity != null) {
            if (StringUtils.isNotEmpty(entity.getOutputNumber())) {
                return ActionResult.fail("单据已经被使用,不允许被删除");
            } else {
                billRuleService.delete(entity);
                return ActionResult.success(MsgCode.SU003.get());
            }
        }
        return ActionResult.fail(MsgCode.FA003.get());
    }

    /**
     * 导出单据规则
     *
     * @param id 打印模板id
     * @return ignore
     */
    @ApiOperation("导出")
    @GetMapping("/{id}/Action/Export")
    public ActionResult export(@PathVariable String id) {
        BillRuleEntity entity = billRuleService.getInfo(id);
        //导出文件
        DownloadVO downloadVO = fileExport.exportFile(entity, configValueUtil.getTemporaryFilePath(), entity.getFullName(), ModuleTypeEnum.SYSTEM_BILLRULE.getTableName());
        return ActionResult.success(downloadVO);
    }

    /**
     * 导入单据规则
     *
     * @param multipartFile 备份json文件
     * @return 执行结果标识
     */
    @ApiOperation("导入")
    @PostMapping(value = "/Action/Import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ActionResult importData(@RequestPart("file") MultipartFile multipartFile) throws DataException {
        //判断是否为.json结尾
        if (FileUtil.existsSuffix(multipartFile, ModuleTypeEnum.SYSTEM_BILLRULE.getTableName())) {
            return ActionResult.fail(MsgCode.IMP002.get());
        }
        //获取文件内容
        String fileContent = FileUtil.getFileContent(multipartFile, configValueUtil.getTemporaryFilePath());
        BillRuleEntity entity = JsonUtil.getJsonToBean(fileContent, BillRuleEntity.class);
        return billRuleService.ImportData(entity);
    }
}
